package com.soriya.nestlive.screen.category

import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.pager.HorizontalPager
import androidx.compose.foundation.pager.rememberPagerState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.ButtonDefaults
import androidx.compose.material.MaterialTheme
import androidx.compose.material.OutlinedButton
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.input.nestedscroll.NestedScrollConnection
import androidx.compose.ui.input.nestedscroll.NestedScrollSource
import androidx.compose.ui.input.nestedscroll.nestedScroll
import androidx.compose.ui.layout.Layout
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.Constraints
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.paging.compose.collectAsLazyPagingItems
import androidx.paging.compose.itemKey
import com.soriya.nestlive.R
import com.soriya.nestlive.component.CustomDivider
import com.soriya.nestlive.component.CustomImage
import com.soriya.nestlive.component.CustomTag
import com.soriya.nestlive.component.LiveTag
import com.soriya.nestlive.component.MediumAdditionalText
import com.soriya.nestlive.component.MediumText
import com.soriya.nestlive.component.MediumTitle
import com.soriya.nestlive.component.NavMenu
import com.soriya.nestlive.component.NavMenuItem
import com.soriya.nestlive.component.ScreenColumnContent
import com.soriya.nestlive.component.SmallText
import com.soriya.nestlive.component.SmallerText
import com.soriya.nestlive.component.VideoCard
import com.soriya.nestlive.constant.UIValue
import com.soriya.nestlive.model.Category
import com.soriya.nestlive.model.Live
import com.soriya.nestlive.model.Video
import com.soriya.nestlive.viewmodel.CategoryModel
import com.soriya.nestlive.viewmodel.LiveModel
import com.soriya.nestlive.viewmodel.VideoModel
import kotlinx.coroutines.launch

@OptIn(ExperimentalFoundationApi::class)
@Composable
fun CategoryDetailScreen(
    categoryId: Long,
    toLiveDetail: (Long) -> Unit,
    toVideoDetail: (Long) -> Unit
) {
    val topHeight = 150.dp
    var topOffset by remember {
        mutableStateOf(0F)
    }

    val maxTopOffset = (topHeight + UIValue.VERTICAL_PADDING.times(2)).value * LocalDensity.current.density

    val listState = rememberLazyListState()

    val isAtTop = remember {
        derivedStateOf {
            !listState.canScrollBackward
        }
    }

    val isAtBottom = remember {
        derivedStateOf {
            !listState.canScrollForward
        }
    }

    val categoryModel: CategoryModel = hiltViewModel()
    val category by categoryModel.categoryDetail.collectAsState()
    categoryModel.getDetail(categoryId)

    val pagerState = rememberPagerState(initialPage = 0)

    val coroutineScope = rememberCoroutineScope()

    ScreenColumnContent(
        modifier = Modifier.padding(top = UIValue.VERTICAL_PADDING)
    ) {
        Layout(
            modifier = Modifier
                .nestedScroll(object : NestedScrollConnection {
                    override fun onPreScroll(
                        available: Offset,
                        source: NestedScrollSource
                    ): Offset {
//                        Log.i("SoRiya", "onPreScroll: $available --- topOffset: $topOffset ${isAtTop.value}")
                        if (available.y < 0) {
                            // 往上划
                            return if (isAtBottom.value) {
                                Offset.Zero
                            } else if (-topOffset < maxTopOffset) {
                                val off = topOffset + available.y
                                topOffset =
                                    if (off < -maxTopOffset) -maxTopOffset else off
                                Offset(0F, available.y)
                            } else {
                                Offset.Zero
                            }
                        } else if (available.y > 0) {
                            // 往下划
                            return if (isAtTop.value) {
                                val off = topOffset + available.y
                                topOffset = if (off > 0) 0F else off
                                Offset(0F, available.y)
                            } else {
                                Offset.Zero
                            }
                        } else {
                            return Offset.Zero
                        }
                    }
                }),
            content = {
                TopInfo(topHeight, category)

                NavMenu {
                    NavMenuItem(title = "直播频道", select = pagerState.currentPage == 0) {
                        coroutineScope.launch {
                            pagerState.animateScrollToPage(0)
                        }
                    }
                    NavMenuItem(title = "视频", select = pagerState.currentPage == 1) {
                        coroutineScope.launch {
                            pagerState.animateScrollToPage(1)
                        }
                    }
                    NavMenuItem(title = "片段", select = pagerState.currentPage == 2) {
                        coroutineScope.launch {
                            pagerState.animateScrollToPage(2)
                        }
                    }
                }

                HorizontalPager(
                    pageCount = 3,
                    state = pagerState,
                    pageSpacing = UIValue.HORIZONTAL_PADDING,
                    modifier = Modifier.weight(1F)
                ) { page ->
                    when (page) {
                        0 -> LiveChannel(categoryId, listState) {
                            toLiveDetail(it)
                        }
                        1 -> Videos(categoryId) {
                            toVideoDetail(it)
                        }
                        2 -> Clips()
                    }
                }
            }
        ) { measurables, constraints  ->
            check(constraints.hasBoundedHeight)
            val height = constraints.maxHeight

            val topPlaceable  = measurables[0].measure(constraints.copy(minHeight = 0, maxHeight = Constraints.Infinity))
            val menuPlaceable = measurables[1].measure(constraints)
            val contentPlaceable = measurables[2].measure(constraints.copy(minHeight = height - menuPlaceable.height - topPlaceable.height, maxHeight = height - menuPlaceable.height))

            layout(constraints.maxWidth, constraints.maxHeight) {
                topPlaceable.placeRelative(0, topOffset.toInt())
                menuPlaceable.placeRelative(0, topPlaceable.height - -topOffset.toInt())
                contentPlaceable.placeRelative(0, topPlaceable.height + menuPlaceable.height - -topOffset.toInt())
            }
        }
    }
}


@Composable
private fun TopInfo(
    height: Dp,
    category: Category
) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .height(height)
    ) {
       CustomImage(
           url = category.cover,
           contentDescription = "Cover",
           shape = RoundedCornerShape(UIValue.LARGE_RADIUS),
           modifier = Modifier
               .size(100.dp, height)
       )

        Spacer(modifier = Modifier.width(20.dp))

        Column(
            verticalArrangement = Arrangement.SpaceBetween,
            modifier = Modifier
                .fillMaxSize()
        ) {
            Text(text = category.categoryName, fontWeight = FontWeight.Bold, fontSize = 22.sp, modifier = Modifier.padding(vertical = 4.dp))

            Row {
                SmallText(text = category.viewers.toString())
                Spacer(modifier = Modifier.width(4.dp))
                SmallText(text = "Viewers", color = MaterialTheme.colors.surface)
                MediumText(text = "·", modifier = Modifier.padding(horizontal = 4.dp))
                SmallText(text = category.followers.toString())
                Spacer(modifier = Modifier.width(4.dp))
                SmallText(text = "Followers", color = MaterialTheme.colors.surface)
            }

            Row {
                category.tags.split("|").forEach {
                    CustomTag(tag = it)
                }
            }

            OutlinedButton(
                onClick = { /*TODO*/ },
                colors = ButtonDefaults.outlinedButtonColors(
                    backgroundColor = MaterialTheme.colors.background
                ),
                border = BorderStroke(1.dp, MaterialTheme.colors.primary),
                shape = RoundedCornerShape(50)
            ) {
                SmallerText(text = "取消订阅")
            }
        }
    }
}

@Composable
private fun LiveChannel(
    categoryId: Long,
    listState: LazyListState,
    toLiveDetail: (Long) -> Unit
) {
    val liveModel: LiveModel = hiltViewModel()

    val items = remember(categoryId) {
        liveModel.getLiveListByCategoryId(categoryId)
    }.collectAsLazyPagingItems()

    if (items.itemCount == 0) {
        Column(
            horizontalAlignment = Alignment.CenterHorizontally,
            verticalArrangement = Arrangement.Center
        ) {
            Spacer(modifier = Modifier.height(20.dp))
            Image(painter = painterResource(id = R.mipmap.empty), contentDescription = "Empty")
            MediumAdditionalText(text = "暂无数据")
        }
    } else Column {
        LazyColumn(
            state = listState,
            modifier = Modifier.fillMaxSize()
        ) {
            items(
                count = items.itemCount,
                key = items.itemKey { it.id!! }
            ) {
                val item = items[it]
                LiveChannelItem(data = item!!) {
                    toLiveDetail(item.channelId)
                }
//                if (it == items.itemCount - 1) CustomDivider(text = "已经到底了")
            }

            item {
                CustomDivider(text = "已经到底了")
            }
        }
    }
}

@Composable
private fun LiveChannelItem(
    data: Live,
    onClick: () -> Unit = {}
) {
    Column(
        modifier = Modifier
            .fillMaxWidth()
            .padding(vertical = UIValue.VERTICAL_PADDING.div(2))
            .clickable(onClick = onClick)
    ) {
        Box {
            CustomImage(
//                url = "https://img.crawler.qq.com/lolwebvideo/0/299e86635bb560191f9f2b1de851e0141706275078/0/",
                url = data.cover,
                contentDescription = "Live Cover",
                shape = RoundedCornerShape(UIValue.LARGE_RADIUS),
                modifier = Modifier
                    .fillMaxWidth()
                    .height(180.dp)
            )

            LiveTag(
                modifier = Modifier
                    .align(Alignment.TopStart)
                    .padding(start = 10.dp, top = 10.dp)
            )
        }

        Row(
            modifier = Modifier
                .padding(vertical = UIValue.VERTICAL_PADDING)
        ) {
            CustomImage(
                url = data.avatar,
                contentDescription = "Avatar",
                shape = CircleShape,
                modifier = Modifier.size(60.dp)
            )

            Spacer(modifier = Modifier.width(20.dp))

            Column {
                MediumTitle(text = data.nickname)
                SmallerText(text = data.liveDesc, color = MaterialTheme.colors.surface, modifier = Modifier.padding(vertical = UIValue.VERTICAL_PADDING.div(2)))
//                SmallerText(text = data, color = MaterialTheme.colors.primary)
                Spacer(modifier = Modifier.height(5.dp))
                Row {
                    data.tags.split("|").forEach {
                        CustomTag(tag = it)
                    }
                }
            }
        }
    }
}

@Composable
private fun Videos(
    categoryId: Long,
    toVideoDetail: (Long) -> Unit = {}
) {
    val videoModel: VideoModel = hiltViewModel()

    val items = remember {
        videoModel.getVideoListByCategoryId(categoryId)
    }.collectAsLazyPagingItems()

    if (items.itemCount == 0) {
        Column(
            horizontalAlignment = Alignment.CenterHorizontally,
            verticalArrangement = Arrangement.Center
        ) {
            Spacer(modifier = Modifier.height(20.dp))
            Image(painter = painterResource(id = R.mipmap.empty), contentDescription = "Empty")
            MediumAdditionalText(text = "暂无数据")
        }
    } else {
        LazyColumn(
            modifier = Modifier.fillMaxSize()
        ) {
            items(
                count = items.itemCount,
                key = items.itemKey { it.id }
            ) {
                val item = items[it]
                VideoCard(data = item!!) {
                    toVideoDetail(item.id)
                }
            }

            item {
                CustomDivider(text = "已经到底了")
            }
        }
    }
}


@Composable
private fun Clips() {
    Text(text = "Clips")
}